package com.lgl.scsapi.filter;

import com.alibaba.fastjson.JSON;
import com.lgl.scsapi.util.utils.AppUtil;
import com.lgl.scsapi.util.utils.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * shiro自定义表单权限认证
 */
public class FormAuthFilter extends FormAuthenticationFilter {

    public FormAuthFilter() {
        super();
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    public boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        HttpServletResponse res = (HttpServletResponse) response;
        Subject currentUser = SecurityUtils.getSubject();
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getServletPath();
        //如果是首页，则不拦截
        if ("/".equals(path) || path.startsWith("/app/index") || path.startsWith("/wx/index")) {
            return true;
        }
        Map<String, Object> noAuthMap = new HashMap<>(2);
        Object userObj = currentUser.getSession().getAttribute(Constants.SESSION_USER);
        //没有登录，需重新登录
        if (userObj == null) {
            noAuthMap.put("status", Constants.NO_LOGIN_CODE);
            AppUtil.responseWrite(res, JSON.toJSONString(noAuthMap));
            return false;
        }
        //没有权限访问
        if (!currentUser.isAuthenticated()) {
            noAuthMap.put("status", Constants.NO_AUTH_CODE);
            AppUtil.responseWrite(res, JSON.toJSONString(noAuthMap));
            return false;
        }
        return true;
    }

}